<template>
  <el-dialog v-model="model" width="500px" align-center append-to-body>
    <template #header>
      <div class="editor-title">{{ $t("merak.edit") }}「{{ $t(`goods_attribute.${props.field}`) }}」</div>
    </template>
    <el-form ref="formRef" label-position="top" :model="value">
      <el-form-item :prop="props.field" :label="$t(`goods_attribute.${props.field}`)">
        <el-radio-group v-if="showRadio" v-model="value[props.field ?? '']">
          <el-radio :value="1">{{ $t("merak.yes") }}</el-radio>
          <el-radio :value="0">{{ $t("merak.no") }}</el-radio>
        </el-radio-group>
        <el-select v-else-if="showTypeSelect" v-model="value[props.field ?? '']" class="qf_select">
          <el-option v-for="option in props.typeOptions" :value="option.key" :label="option.value" />
        </el-select>
        <el-select v-else-if="showGroupSelect" v-model="value[props.field ?? '']" class="qf_select">
          <el-option v-for="option in props.groupOptions" :value="option.key" :label="option.value" />
        </el-select>
        <el-input v-else-if="showNumberInput" v-model="value[props.field ?? '']" v-num class="qf_input" />
        <el-input v-else v-model="value[props.field ?? '']" class="qf_input" @input="handlePrefixTrim" @change="handleTrim" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="model = false">{{ $t("merak.cancel") }}</el-button>
      <el-button type="primary" :disabled="disabled" :loading="loading" @click="handleSave">{{ $t("merak.confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx">
import type { MerakXTableEditorParams } from "@/components/MerakXTable";

import { getCurrentInstance, ref, reactive, computed, watch } from "vue";

import {
  ElMessage,
  ElDialog,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadioGroup,
  ElRadio,
  ElSelect,
  ElOption
} from "element-plus";

import { ResultEnum } from "@/enums/httpEnum";
import { RouteType, TabType, OptionType, editCell } from "@/api/modules/goodsArchive/allocation";

const props = defineProps<
  Partial<MerakXTableEditorParams> & { type: RouteType; tab: TabType; typeOptions: OptionType[]; groupOptions: OptionType[] }
>();

const emit = defineEmits<{
  update: [params: MerakXTableEditorParams & { optionText?: string }];
}>();

const model = defineModel<boolean>({ default: false });

const currentInstance = getCurrentInstance();

const formRef = ref<InstanceType<typeof ElForm>>();

const loading = ref(false);

const value = reactive<Record<string, any>>({
  [props.field!]: props.value
});

const disabled = computed(() => !props.field || value[props.field] === undefined || value[props.field] === "");

const showRadio = computed(() =>
  [
    "display_detail",
    "display_filter",
    "display_detail_focal",
    "is_required",
    "cc_is_required",
    "is_spec",
    "is_search",
    "for_sku",
    "is_number",
    "un_editable_checked"
  ].includes(props.field ?? "")
);

const showTypeSelect = computed(() => ["prop_type", "cc_prop_type"].includes(props.field ?? ""));

const showGroupSelect = computed(() => ["prop_group", "cc_prop_group"].includes(props.field ?? ""));

const showNumberInput = computed(() =>
  ["prop_group_sort", "prop_sort_detail", "prop_sort_filter", "sort_prop_detail_focal", "sort", "cc_prop_group_sort"].includes(
    props.field ?? ""
  )
);

const handleSave = () => {
  formRef.value?.validate().then(async () => {
    const field = props.field ?? "";
    const cellValue = value[field];
    const payload = {
      prop_id: props.rowKey,
      attribute: field,
      value: cellValue
    };
    loading.value = true;
    await editCell[props.tab](props.type, payload)
      .then(({ code, message }) => {
        if (code == ResultEnum.SUCCESS) {
          let text: string | undefined;
          if (
            [
              "display_detail",
              "display_filter",
              "display_detail_focal",
              "is_required",
              "cc_is_required",
              "is_spec",
              "is_search",
              "is_number",
              "un_editable_checked"
            ].includes(field)
          ) {
            text =
              cellValue === 1
                ? currentInstance?.proxy?.$t("merak.yes")
                : cellValue === 0
                  ? currentInstance?.proxy?.$t("merak.no")
                  : undefined;
          }
          if (["prop_type", "cc_prop_type"].includes(field)) {
            text = props.typeOptions.find(option => option.key === cellValue)?.value;
          }
          if (["prop_group", "cc_prop_group"].includes(field)) {
            text = props.groupOptions.find(option => option.key === cellValue)?.value;
          }
          emit("update", { rowKey: props.rowKey ?? "", field, value: cellValue, text });
          model.value = false;
          ElMessage.success(currentInstance?.proxy?.$t("goods_attribute.row_edit_success"));
        } else {
          const msg = typeof message === "string" ? message : Object.values(message)?.[0];
          ElMessage.error(msg);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  });
};

// 处理输入框开头空格
const handlePrefixTrim = (val: string) => {
  value[props.field!] = val.replace(/^\s+/g, "");
};

// 处理输入框尾部空格
const handleTrim = (val: string) => {
  value[props.field!] = val.trim();
};

watch(
  () => props,
  () => {
    if (!!props) {
      Object.keys(value).forEach(key => (value[key] = undefined));
      value[props.field!] = props.value;
    }
  },
  { deep: true }
);
</script>
